package cn.itcast.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Component
@Aspect
public class AddCreateTimeAspect {
    @Around("@annotation(cn.itcast.annotation.AddAnnotation)")
    public Object enhanceAdd(ProceedingJoinPoint pjp) throws Throwable {
        Object[] args = pjp.getArgs();
        Object obj = args[0];
        /*Class<?> clazz = obj.getClass();
        Field declaredField = clazz.getDeclaredField("createTime");
        declaredField.setAccessible(true);
        declaredField.set(obj, LocalDateTime.now());
        Object proceed = pjp.proceed(args);*/
        Class<?> clazz = obj.getClass();
        new PropertyDescriptor("createTime", clazz).getWriteMethod().invoke(obj, LocalDateTime.now());
        new PropertyDescriptor("updateTime", clazz).getWriteMethod().invoke(obj, LocalDateTime.now());
        Object proceed = pjp.proceed();
        return proceed;
    }
}
